<template>
  <div class="collections-container">
    <div class="collections-header">
      <h1 class="page-title">馆藏精品</h1>
      <p class="page-subtitle">探索珍贵文物，感受历史魅力</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索藏品名称"
        class="search-input"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select
        v-model="selectedLocation"
        placeholder="选择展厅"
        clearable
        class="location-select"
      >
        <el-option
          v-for="location in locations"
          :key="location"
          :label="location"
          :value="location"
        />
      </el-select>

      <el-select
        v-model="selectedCategoryId"
        placeholder="选择分类"
        clearable
        class="category-select"
      >
        <el-option
          v-for="category in categoryList"
          :key="category.id"
          :label="category.name"
          :value="category.id"
        />
      </el-select>
     <el-button type="primary" @click="showAppointmentDialog">预约讲解员</el-button>
    </div>

    <!-- 展示统计信息 -->
    <div class="stats-section">
      <el-text class="stats-text">
        共展示 {{ filteredCollections.length }} 件藏品
      </el-text>
    </div>

    <!-- 藏品展示网格 -->
    <div class="collections-grid" v-loading="loading">
      <template v-if="filteredCollections.length">
        <el-card
          v-for="item in filteredCollections"
          :key="item.id"
          class="collection-card"
          :body-style="{ padding: '0px' }"
          @click="showDetail(item)"
        >
          <div class="collection-image">
            <img :src="item.imageUrl" :alt="item.name">
          </div>
          <div class="collection-info">
            <h3>{{ item.name }}</h3>
            <p class="location">{{ item.location }}</p>
            <p class="description">{{ item.description }}</p>
          </div>
        </el-card>
      </template>
      <el-empty
        v-else
        description="暂无符合条件的藏品"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="selectedItem?.name"
      width="70%"
      class="collection-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <div class="dialog-content" v-if="selectedItem">
        <div class="dialog-image">
          <img :src="selectedItem.imageUrl" :alt="selectedItem.name">
        </div>
        <div class="dialog-info">
          <h3>{{ selectedItem.name }}</h3>
          <p class="location">
            <el-icon><Location /></el-icon>
            展厅位置：{{ selectedItem.location }}
          </p>
          <p class="category">
            <el-icon><Collection /></el-icon>
            分类：{{ getCategoryName(selectedItem.categoryId) }}
          </p>
          <div class="description">
            <h4>藏品简介</h4>
            <p>{{ selectedItem.description }}</p>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 预约讲解员对话框 -->
    <el-dialog
      v-model="appointmentDialogVisible"
      title="预约讲解员"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <el-form 
        :model="appointmentForm" 
        :rules="appointmentRules" 
        ref="appointmentFormRef" 
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="预约日期" prop="appointmentDate">
          <el-date-picker
            v-model="appointmentForm.appointmentDate"
            type="date"
            placeholder="选择预约日期"
            :disabled-date="disabledDate"
            style="width: 100%"
            @change="fetchTimeSlots"
          />
        </el-form-item>
        
        <el-form-item label="时间段" prop="timeSlotId">
          <el-select 
            v-model="appointmentForm.timeSlotId" 
            placeholder="请选择时间段"
            style="width: 100%"
            :disabled="!appointmentForm.appointmentDate"
          >
            <el-option
              v-for="slot in timeSlots"
              :key="slot.id"
              :label="slot.startTime + ' - ' + slot.endTime"
              :value="slot.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="姓名" prop="visitorName">
          <el-input v-model="appointmentForm.visitorName" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="visitorPhone">
          <el-input v-model="appointmentForm.visitorPhone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="参观人数" prop="visitorCount">
          <el-input-number 
            v-model="appointmentForm.visitorCount" 
            :min="1" 
            :max="20" 
            placeholder="请输入参观人数" 
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="预约藏品" prop="collectionIds">
          <el-select
            v-model="appointmentForm.collectionIds"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择藏品（可多选）"
            style="width: 100%"
          >
            <el-option
              v-for="item in collections"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="appointmentForm.remark" 
            type="textarea" 
            placeholder="请输入备注信息（选填）" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="appointmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAppointment" :loading="submitting">
            确认预约
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { Search, Location, Collection } from '@element-plus/icons-vue'
// 移除本地数据导入
// import { collections } from '@/data/collections'
// 导入API方法
import { getCollectionsPage } from '@/api/collections'
import { getCategoryList } from '@/api/category'
import { ElMessage, FormInstance } from 'element-plus'
import { getEnabledTimeSlots } from '@/api/timeSlot'
import { saveGuideAppointment } from '@/api/guideAppointment'
import { useStore } from 'vuex'
// 获取用户信息
const store = useStore()
const userInfo = computed(() => store.getters.userInfo)
// 状态管理
const searchQuery = ref('')
const selectedLocation = ref('')
const selectedCategoryId = ref('')
const loading = ref(true)
const dialogVisible = ref(false)
const selectedItem = ref(null)
const collections = ref([])
const categoryList = ref([])

// 获取所有展厅位置
const locations = computed(() => {
  const locationSet = new Set(collections.value.map(item => item.location))
  return Array.from(locationSet).sort()
})

// 根据搜索和筛选条件过滤藏品
const filteredCollections = computed(() => {
  let result = collections.value

  if (selectedLocation.value) {
    result = result.filter(item => item.location === selectedLocation.value)
  }

  if (selectedCategoryId.value) {
    result = result.filter(item => item.categoryId === selectedCategoryId.value)
  }

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(item =>
      item.name.toLowerCase().includes(query) ||
      item.description.toLowerCase().includes(query)
    )
  }

  return result
})

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  if (!categoryId) return '未分类'
  const category = categoryList.value.find(item => item.id === categoryId)
  return category ? category.name : '未知分类'
}

// 显示详情
const showDetail = (item) => {
  selectedItem.value = item
  dialogVisible.value = true
}

// 获取藏品数据
const fetchCollections = async () => {
  loading.value = true
  try {
    const res = await getCollectionsPage({
      size: -1,
      current: 1
    })
    console.log(res)

    collections.value = res.records || []
  } catch (error) {
    console.error('获取藏品数据出错:', error)
    ElMessage.error('获取藏品数据出错')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const res = await getCategoryList()
    console.log(res)
    categoryList.value = res || []
  } catch (error) {
    console.error('获取分类列表出错:', error)
    ElMessage.error('获取分类列表出错')
  }
}

// 预约相关状态
const appointmentDialogVisible = ref(false)
const appointmentFormRef = ref<FormInstance>()
const timeSlots = ref([])
const submitting = ref(false)

// 预约表单
const appointmentForm = reactive({
  appointmentDate: null,
  timeSlotId: '',
  visitorName: '',
  visitorPhone: '',
  visitorCount: 1,
  collectionIds: [],
  remark: ''
})

// 表单验证规则
const appointmentRules = {
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  timeSlotId: [
    { required: true, message: '请选择时间段', trigger: 'change' }
  ],
  visitorName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应在2至20个字符之间', trigger: 'blur' }
  ],
  visitorPhone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  visitorCount: [
    { required: true, message: '请输入参观人数', trigger: 'change' },
    { type: 'number', min: 1, max: 20, message: '参观人数应在1至20人之间', trigger: 'change' }
  ],
  collectionIds: [
    { required: true, message: '请至少选择一个藏品', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一个藏品', trigger: 'change' }
  ]
}

// 禁用今天之前的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 显示预约对话框
const showAppointmentDialog = () => {
  appointmentDialogVisible.value = true
}

// 根据选择的日期获取可用时间段
const fetchTimeSlots = async () => {
  if (!appointmentForm.appointmentDate) return
  
  try {
    const res = await getEnabledTimeSlots()
    timeSlots.value = res || []
    
    // 重置已选时间段
    appointmentForm.timeSlotId = ''
  } catch (error) {
    console.error('获取时间段失败:', error)
    ElMessage.error('获取可用时间段失败')
  }
}

// 提交预约
const submitAppointment = async () => {
  if (!appointmentFormRef.value) return
  
  await appointmentFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        
        // 构建藏品名称字符串
        const selectedCollectionNames = appointmentForm.collectionIds.map(id => {
          const collection = collections.value.find(c => c.id === id)
          return collection ? collection.name : ''
        }).filter(Boolean).join(',')
        
        const formData = {
          ...appointmentForm,
          userId:userInfo.value.userInfo.id, // 添加用户ID
          appointmentDate: appointmentForm.appointmentDate ? new Date(appointmentForm.appointmentDate).toISOString().split('T')[0] : '',
          collectionIds: appointmentForm.collectionIds.join(','),
          collectionNames: selectedCollectionNames // 添加藏品名称字符串
        }
        
        await saveGuideAppointment(formData)
        ElMessage.success('预约讲解员成功')
        appointmentDialogVisible.value = false
        resetAppointmentForm()
      } catch (error) {
        console.error('预约失败:', error)
        ElMessage.error('预约失败，请稍后重试')
      } finally {
        submitting.value = false
      }
    } else {
      ElMessage.warning('请完善表单信息')
      return false
    }
  })
}

// 重置预约表单
const resetAppointmentForm = () => {
  appointmentForm.appointmentDate = null
  appointmentForm.timeSlotId = ''
  appointmentForm.visitorName = ''
  appointmentForm.visitorPhone = ''
  appointmentForm.visitorCount = 1
  appointmentForm.collectionIds = []
  appointmentForm.remark = ''
  timeSlots.value = []
  
  // 重置表单验证
  if (appointmentFormRef.value) {
    appointmentFormRef.value.resetFields()
  }
}

// 生命周期钩子
onMounted(() => {
  Promise.all([fetchCollections(), fetchCategoryList()])
})
</script>

<style scoped>
.collections-container {
  padding: 24px;
  max-width: 1280px;
  margin: 0 auto;
}

.collections-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  color: #2c3e50;
  font-size: 32px;
  margin: 0 0 12px;
}

.page-subtitle {
  color: #606266;
  font-size: 16px;
  margin: 0;
}

.filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.search-input {
  width: 300px;
}

.location-select,
.category-select {
  width: 200px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-text {
  color: #606266;
  font-size: 14px;
}

.collections-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  min-height: 400px;
}

.collection-card {
  cursor: pointer;
  transition: all 0.3s;
}

.collection-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.collection-image {
  height: 200px;
  overflow: hidden;
}

.collection-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.collection-card:hover .collection-image img {
  transform: scale(1.05);
}

.collection-info {
  padding: 16px;
}

.collection-info h3 {
  margin: 0 0 8px;
  font-size: 18px;
  color: #303133;
}

.location {
  color: #909399;
  font-size: 14px;
  margin-bottom: 8px;
}

.description {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  max-height: 120px;
  overflow-y: auto;
  padding-right: 5px;
}

.description::-webkit-scrollbar {
  width: 4px;
}

.description::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 2px;
}

.description::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.collection-dialog .dialog-content {
  display: flex;
  gap: 32px;
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-image {
  flex: 0 0 45%;
  position: sticky;
  top: 0;
}

.dialog-image img {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dialog-info {
  flex: 1;
  padding-right: 16px;
}

.dialog-info h3 {
  margin: 0 0 20px;
  font-size: 24px;
  color: #303133;
  line-height: 1.4;
}

.dialog-info .location,
.dialog-info .category {
  color: #606266;
  margin-bottom: 12px;
  font-size: 16px;
}

.dialog-info .description {
  margin-top: 24px;
  max-height: none;
  overflow: visible;
}

.dialog-info .description h4 {
  margin: 0 0 16px;
  color: #303133;
  font-size: 18px;
}

.dialog-info .description p {
  color: #606266;
  line-height: 1.8;
  font-size: 15px;
  text-align: justify;
  margin: 0;
}

@media (max-width: 768px) {
  .collections-container {
    padding: 16px;
  }

  .filter-section {
    flex-direction: column;
  }

  .search-input,
  .location-select,
  .category-select {
    width: 100%;
  }

  .collections-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }

  .collection-dialog .dialog-content {
    flex-direction: column;
    gap: 24px;
  }

  .dialog-image {
    position: relative;
    flex: none;
  }

  .dialog-info {
    padding-right: 0;
  }

  .dialog-info h3 {
    font-size: 20px;
    margin-bottom: 16px;
  }

  .dialog-info .description h4 {
    font-size: 16px;
  }

  .dialog-info .description p {
    font-size: 14px;
  }
}
</style> 